package com.cjx.auth.config;

import com.cjx.auth.domian.SecurityUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

/**
*@Description Oatuh2整合jwt配置
*@Verson v1.0.0
*@Author cjunxian
*@Date
*/
@Configuration
public class JWTOauth2Config {

    /**
     * 使用非对称加密算法对token签名
     */
    @Bean(name = "jwtAccessTokenConverter")
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyPair());
        return converter;
    }

    /**
     * 从classpath下的密钥库中获取密钥对(公钥+私钥)
     */
    @Bean(name = "jwtKeyPair")
    public KeyPair keyPair() {
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(
                new ClassPathResource("cjx.jks"), "123000".toCharArray());
        KeyPair keyPair = factory.getKeyPair(
                "cjx-key", "123000".toCharArray());
        return keyPair;
    }

    /**
     * JWT内容增强
     */
    @Bean(name = "jwtTokenEnhancer")
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            Map<String, Object> map = new HashMap<>(2);
            SecurityUser user = (SecurityUser) authentication.getUserAuthentication().getPrincipal();
            map.put("user_id",user.getId());
            map.put("client_id", user.getClientId());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
            return accessToken;
        };
    }
}
